<?php
// +----------------------------------------------------------------------
// | ThinkPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2007 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 杨庆  393978119@qq.com
// +----------------------------------------------------------------------
// $Id$
//公共函数
function erwei($cate, $pid = 0)
{
    $arr = array();
    foreach ($cate as $v) {
        if ($v['pid'] == $pid) {
            if ($v['ismenu'] == 1) {
                $v['child'] = erwei($cate, $v['id']);
                $arr[] = $v;
            }
        }
    }
    return $arr;
}

function toDate($time, $format = 'Y-m-d H:i:s')
{
    if (empty($time)) {
        return '';
    }
    $format = str_replace('#', ':', $format);
    return date($format, $time);
}

// 缓存文件
function cmssavecache($name = '', $fields = '')
{
    $Model = D($name);
    $list = $Model->select();
    $data = array();
    foreach ($list as $key => $val) {
        if (empty($fields)) {
            $data[$val[$Model->getPk()]] = $val;
        } else {
            // 获取需要的字段
            if (is_string($fields)) {
                $fields = explode(',', $fields);
            }
            if (count($fields) == 1) {
                $data[$val[$Model->getPk()]] = $val[$fields[0]];
            } else {
                foreach ($fields as $field) {
                    $data[$val[$Model->getPk()]][] = $val[$field];
                }
            }
        }
    }
    $savefile = cmsgetcache($name);
    // 所有参数统一为大写
    $content = "<?php\nreturn " . var_export(array_change_key_case($data, CASE_UPPER), true) . ";\n?>";
    file_put_contents($savefile, $content);
}

function cmsgetcache($name = '')
{
    return DATA_PATH . '~' . strtolower($name) . '.php';
}

function getStatus($status, $imageShow = true)
{
    switch ($status) {
        case 0:
            $showText = '禁用';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/locked.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="禁用">';
            break;
        case 2:
            $showText = '待审';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/prected.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="待审">';
            break;
        case -1:
            $showText = '删除';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/del.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="删除">';
            break;
        case 1:
        default:
            $showText = '正常';
            $showImg = '<IMG SRC="' . WEB_PUBLIC_PATH . '/Images/ok.gif" WIDTH="20" HEIGHT="20" BORDER="0" ALT="正常">';
    }
    return ($imageShow === true) ? $showImg : $showText;
}

function getDefaultStyle($style)
{
    if (empty($style)) {
        return 'blue';
    } else {
        return $style;
    }
}

function IP($ip = '', $file = 'UTFWry.dat')
{
    $_ip = array();
    if (isset($_ip[$ip])) {
        return $_ip[$ip];
    } else {
        import("ORG.Net.IpLocation");
        $iplocation = new IpLocation($file);
        $location = $iplocation->getlocation($ip);
        $_ip[$ip] = $location['country'] . $location['area'];
    }
    return $_ip[$ip];
}

//function getIp(){
//    $onlineip='';
//    if(getenv('HTTP_CLIENT_IP')&&strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')){
//        $onlineip=getenv('HTTP_CLIENT_IP');
//    } elseif(getenv('HTTP_X_FORWARDED_FOR')&&strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')){
//        $onlineip=getenv('HTTP_X_FORWARDED_FOR');
//    } elseif(getenv('REMOTE_ADDR')&&strcasecmp(getenv('REMOTE_ADDR'),'unknown')){
//        $onlineip=getenv('REMOTE_ADDR');
//    } elseif(isset($_SERVER['REMOTE_ADDR'])&&$_SERVER['REMOTE_ADDR']&&strcasecmp($_SERVER['REMOTE_ADDR'],'unknown')){
//        $onlineip=$_SERVER['REMOTE_ADDR'];
//    }
//    return $onlineip;
//}
function getNodeName($id)
{
    if (Session::is_set('nodeNameList')) {
        $name = Session::get('nodeNameList');
        return $name[$id];
    }
    $Group = D("Node");
    $list = $Group->getField('id,name');
    $name = $list[$id];
    Session::set('nodeNameList', $list);
    return $name;
}

function get_pawn($pawn)
{
    if ($pawn == 0) {
        return "<span style='color:green'>没有</span>";
    } else {
        return "<span style='color:red'>有</span>";
    }
}

function get_patent($patent)
{
    if ($patent == 0) {
        return "<span style='color:green'>没有</span>";
    } else {
        return "<span style='color:red'>有</span>";
    }
}

function getCardStatus($status)
{
    switch ($status) {
        case 0:
            $show = '未启用';
            break;
        case 1:
            $show = '已启用';
            break;
        case 2:
            $show = '使用中';
            break;
        case 3:
            $show = '已禁用';
            break;
        case 4:
            $show = '已作废';
            break;
    }
    return $show;
}

// zhanghuihua@msn.com
function showStatus($status, $id, $callback = "")
{
    switch ($status) {
        case 0:
            $info = '<a href="__URL__/resume/id/' . $id . '/navTabId/__MODULE__" target="ajaxTodo" callback="' . $callback . '">恢复</a>';
            break;
        case 2:
            $info = '<a href="__URL__/pass/id/' . $id . '/navTabId/__MODULE__" target="ajaxTodo" callback="' . $callback . '">批准</a>';
            break;
        case 1:
            $info = '<a href="__URL__/forbid/id/' . $id . '/navTabId/__MODULE__" target="ajaxTodo" callback="' . $callback . '">禁用</a>';
            break;
        case -1:
            $info = '<a href="__URL__/recycle/id/' . $id . '/navTabId/__MODULE__" target="ajaxTodo" callback="' . $callback . '">还原</a>';
            break;
    }
    return $info;
}

/**
 * +----------------------------------------------------------
 * 获取登录验证码 默认为4位数字
 * +----------------------------------------------------------
 * @param string $fmode 文件名
 * +----------------------------------------------------------
 * @return string
 * +----------------------------------------------------------
 */
function build_verify($length = 4, $mode = 1)
{
    return rand_string($length, $mode);
}

function getGroupName($id)
{
    if ($id == 0) {
        return '无上级组';
    }
    if ($list = F('groupName')) {
        return $list[$id];
    }
    $dao = D("Role");
    $list = $dao->select(array(
        'field' => 'id,name',
    ));
    foreach ($list as $vo) {
        $nameList[$vo['id']] = $vo['name'];
    }
    $name = $nameList[$id];
    F('groupName', $nameList);
    return $name;
}

function sort_by($array, $keyname = null, $sortby = 'asc')
{
    $myarray = $inarray = array();
    # First store the keyvalues in a seperate array
    foreach ($array as $i => $befree) {
        $myarray[$i] = $array[$i][$keyname];
    }
    # Sort the new array by
    switch ($sortby) {
        case 'asc':
            # Sort an array and maintain index association...
            asort($myarray);
            break;
        case 'desc':
        case 'arsort':
            # Sort an array in reverse order and maintain index association
            arsort($myarray);
            break;
        case 'natcasesor':
            # Sort an array using a case insensitive "natural order" algorithm
            natcasesort($myarray);
            break;
    }
    # Rebuild the old array
    foreach ($myarray as $key => $befree) {
        $inarray[] = $array[$key];
    }
    return $inarray;
}

/**
 * +----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码
 * 默认长度6位 字母和数字混合 支持中文
 * +----------------------------------------------------------
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
 * +----------------------------------------------------------
 * @return string
 * +----------------------------------------------------------
 */
function rand_string($len = 6, $type = '', $addChars = '')
{
    $str = '';
    switch ($type) {
        case 0:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        case 1:
            $chars = str_repeat('0123456789', 3);
            break;
        case 2:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
            break;
        case 3:
            $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
            break;
        default:
            // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
            $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
            break;
    }
    if ($len > 10) { //位数过长重复字符串一定次数
        $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
    }
    if ($type != 4) {
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
    } else {
        // 中文随机字
        for ($i = 0; $i < $len; $i++) {
            $str .= msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1);
        }
    }
    return $str;
}

function pwdHash($password, $type = 'md5')
{
    return hash($type, $password);
}

/* zhanghuihua */
function percent_format($number, $decimals = 0)
{
    return number_format($number * 100, $decimals) . '%';
}

/**
 * 动态获取数据库信息
 * @param $tname 表名
 * @param $where 搜索条件
 * @param $order 排序条件 如："id desc";
 * @param $count 取前几条数据
 */
function findList($tname, $where = "", $order, $count)
{
    $m = M($tname);
    if (!empty($where)) {
        $m->where($where);
    }
    if (!empty($order)) {
        $m->order($order);
    }
    if ($count > 0) {
        $m->limit($count);
    }
    return $m->select();
}

function findById($name, $id)
{
    $m = M($name);
    return $m->find($id);
}

function attrById($name, $attr, $id)
{
    $m = M($name);
    $a = $m->where('id=' . $id)->getField($attr);
    return $a;
}

/**
 * 函数名称: getPhoneNumber
 * 函数功能: 取手机号
 * 输入参数: none
 * 函数返回值: 成功返回号码，失败返回false
 * 其它说明: 说明
 */
function getPhoneNumber()
{
    if (isset($_SERVER['HTTP_X_NETWORK_INFO'])) {
        $str1 = $_SERVER['HTTP_X_NETWORK_INFO'];
        $getstr1 = preg_replace('/(.*,)(11[d])(,.*)/i', '\2', $str1);
        return $getstr1;
    } elseif (isset($_SERVER['HTTP_X_UP_CALLING_LINE_ID'])) {
        $getstr2 = $_SERVER['HTTP_X_UP_CALLING_LINE_ID'];
        return $getstr2;
    } elseif (isset($_SERVER['HTTP_X_UP_SUBNO'])) {
        $str3 = $_SERVER['HTTP_X_UP_SUBNO'];
        $getstr3 = preg_replace('/(.*)(11[d])(.*)/i', '\2', $str3);
        return $getstr3;
    } elseif (isset($_SERVER['DEVICEID'])) {
        return $_SERVER['DEVICEID'];
    } else {
        return false;
    }
}

/**
 * 函数名称: getHttpHeader
 * 函数功能: 取头信息
 * 输入参数: none
 * 函数返回值: 成功返回号码，失败返回false
 * 其它说明: 说明
 */
function getHttpHeader()
{
    $str = '';
    foreach ($_SERVER as $key => $val) {
        $gstr = str_replace("&", "&", $val);
        $str .= "$key -> " . $gstr . "\r\n";
    }
    return $str;
}

/**
 * 函数名称: getUA
 * 函数功能: 取UA
 * 输入参数: none
 * 函数返回值: 成功返回号码，失败返回false
 * 其它说明: 说明
 */
function getUA()
{
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        return $_SERVER['HTTP_USER_AGENT'];
    } else {
        return false;
    }
}

/**
 * 函数名称: getPhoneType
 * 函数功能: 取得手机类型
 * 输入参数: none
 * 函数返回值: 成功返回string，失败返回false
 * 其它说明: 说明
 */
function getPhoneType()
{
    $ua = getUA();
    if ($ua != false) {
        $str = explode(' ', $ua);
        return $str[0];
    } else {
        return false;
    }
}

/**
 * 函数名称: isOpera
 * 函数功能: 判断是否是opera
 * 输入参数: none
 * 函数返回值: 成功返回string，失败返回false
 * 其它说明: 说明
 */
function isOpera()
{
    $uainfo = getUA();
    if (preg_match('/.*Opera.*/i', $uainfo)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 函数名称: isM3gate
 * 函数功能: 判断是否是m3gate
 * 输入参数: none
 * 函数返回值: 成功返回string，失败返回false
 * 其它说明: 说明
 */
function isM3gate()
{
    $uainfo = getUA();
    if (preg_match('/M3Gate/i', $uainfo)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 函数名称: getHttpAccept
 * 函数功能: 取得HA
 * 输入参数: none
 * 函数返回值: 成功返回string，失败返回false
 * 其它说明: 说明
 */
function getHttpAccept()
{
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        return $_SERVER['HTTP_ACCEPT'];
    } else {
        return false;
    }
}

/**
 * 函数名称: getIP
 * 函数功能: 取得手机IP
 * 输入参数: none
 * 函数返回值: 成功返回string
 * 其它说明: 说明
 */
function getIP()
{
    $ip = getenv('REMOTE_ADDR');
    $ip_ = getenv('HTTP_X_FORWARDED_FOR');
    if (($ip_ != "") && ($ip_ != "unknown")) {
        $ip = $ip_;
    }
    return $ip;
}

function getaccess()
{
    M('node')->query('truncate node');
}

function get_url()
{
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}

function SendMail($to, $title, $content)
{
    Vendor('PHPMailer.PHPMailerAutoload');
    $mail = new \PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    $mail->Host = "smtp.163.com"; //smtp服务器的名称（这里以QQ邮箱为例）
    // $mail->Host = 'ssl://smtp.163.com'; # 阿里云线上使用ssl加密方式
    $mail->SMTPAuth = true; //启用smtp认证
    $mail->SMTPSecure = 'ssl'; //设置使用ssl加密方式登录鉴权
    $mail->Port = 465;
    // $mail->Username = "yq5858588@163.com";
    // $mail->Password = "yq123456";
    $mail->Username = "wnyxwap@163.com";
    $mail->Password = "zxj19880502";
    $mail->From = "wnyxwap@163.com";
    $mail->FromName = "发件人姓名"; //发件人姓名
    $mail->AddAddress($to, "尊敬的客户");
    $mail->WordWrap = 50; //设置每行字符长度
    $mail->IsHTML(true); // 是否HTML格式邮件
    $mail->CharSet = 'UTF-8'; //设置邮件编码
    $mail->Subject = $title; //邮件主题
    $mail->Body = $content; //邮件内容
    $mail->AltBody = "text/html"; //邮件正文不支持HTML的备用显示
    $flag = $mail->Send();
    if ($flag) {
        return $flag;
    } else {
        return ($mail->ErrorInfo);
    }
}

// 获取子串，该函数主要处理双字节字符，使其截取时不会出现错乱
function cut($str, $len, $cut_flag = '...')
{
    if (strlen($str) <= $len) {
        return $str;
    }
    $nmax = $cut_flag ? ($len - strlen($cut_flag)) : $len;
    $out = "";
    for ($ni = 0; $ni < $nmax; $ni++) {
        $char = sub_str($str, $ni); //substr($str, $ni, 1);
        if (ord($char) > 128) {
            $char .= substr($str, ++$ni, 1);
        }
        if (strlen($out) + strlen($char) <= $nmax) {
            $out .= $char;
        }
    }
    return $out . $cut_flag;
}

function getTongbiDays()
{
    $t = time();
    $firstday = date('Y-m-01 H:i:s', strtotime(date('Y', $t) . '-' . (date('m', $t) - 1) . '-01'));
    $nowday = date("d", time());
    $lastmonthTotalday = date("t", date("m", time() - 1));
    if ($nowday >= $lastmonthTotalday) {
        $endday = $lastmonthTotalday;
    } else {
        $endday = $nowday;
    }
    date("t", date("m", $t) - 1);
    $lastday = mktime(23, 59, 59, date("m", $t) - 1, $endday, date("Y", $t));
    $lastday = date("Y-m-d H:i:s", $lastday);
    return array($firstday, $lastday);
}

function getMonthDays_new($month = "this month", $format = "Y-m-d", $dateTimeZone = false)
{
    if (!$dateTimeZone) {
        $dateTimeZone = new DateTimeZone("Asia/Shanghai");
    }
    $start = new DateTime("first day of $month", $dateTimeZone);
    $end = new DateTime("last day of $month", $dateTimeZone);
    $days = array();
    for ($time = $start; $time <= $end; $time = $time->modify("+1 day")) {
        $days[] = $time->format($format);
    }
    return $days;
}

///////兼容php5.2的获取时间的函数
function getMonthDays($month = "this month", $format = "Y-m-d")
{
    $start = strtotime(date('Y-m-01', strtotime($month)));
    $end = strtotime(date('Y-m-d', strtotime(date('Y-m-01', strtotime($month)) . ' +1 month -1 day')));
    $days = array();
    for ($i = $start; $i <= $end; $i += 24 * 3600) {
        $days[] = date($format, $i);
    }
    return $days;
}

function getMonths($month = "this month", $format = "Y-m-d")
{
    $days[] = date('Y-01', strtotime($month));
    $days[] = date('Y-02', strtotime($month));
    $days[] = date('Y-03', strtotime($month));
    $days[] = date('Y-04', strtotime($month));
    $days[] = date('Y-05', strtotime($month));
    $days[] = date('Y-06', strtotime($month));
    $days[] = date('Y-07', strtotime($month));
    $days[] = date('Y-08', strtotime($month));
    $days[] = date('Y-09', strtotime($month));
    $days[] = date('Y-10', strtotime($month));
    $days[] = date('Y-11', strtotime($month));
    $days[] = date('Y-12', strtotime($month));
    return $days;
}

function getMonthsByTwoTime($time1, $time2)
{
    $time1 = strtotime($time1);
    $time2 = strtotime($time2);
    $monarr = array();
    for ($i = $time1; $i <= $time2; $i += strtotime('+1 month', date('Y-m', $i))) {
        $temp = date('Y-m', $i); // 取得递增月;
        $monarr[] = $temp;
    }
    return ($monarr);
}

function getDays($Date1, $Date2)
{
    $j = 0;
    for ($i = strtotime($Date1); $i <= strtotime($Date2); $i += 86400) {
        $ThisDate = date("Y-m-d", $i);
        $res[] = $ThisDate;
    }
    return $res;
}

function getHtml($url)
{
    if (function_exists('file_get_contents')) {
        $file_contents = file_get_contents($url);
    } else {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file_contents = curl_exec($ch);
        curl_close($ch);
    }
    return $file_contents;
}

// 方法二：通过截取年、月、日来进行比较计算，更简单
function getGongling($idcard)
{
    $year = substr($idcard, 6, 4);
    $monthDay = substr($idcard, 10, 4);
    $age = date('Y') - $year;
    if ($monthDay > date('md')) {
        $age--;
    }
    return $age;
}

function getIDCardInfo($IDCard, $format = 0)
{
    $result['error'] = 0;//0：未知错误，1：身份证格式错误，2：无错误 
    $result['flag'] = '';//0标示成年，1标示未成年 
    $result['tdate'] = '';//生日，格式如：2012-11-15 
    if (!preg_match("/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/", $IDCard)) {
        $result['error'] = 1;
        return $result;
    } else {
        if (strlen($IDCard) == 18) {
            $tyear = intval(substr($IDCard, 6, 4));
            $tmonth = intval(substr($IDCard, 10, 2));
            $tday = intval(substr($IDCard, 12, 2));
        } elseif (strlen($IDCard) == 15) {
            $tyear = intval("19" . substr($IDCard, 6, 2));
            $tmonth = intval(substr($IDCard, 8, 2));
            $tday = intval(substr($IDCard, 10, 2));
        }
        if ($tyear > date("Y") || $tyear < (date("Y") - 100)) {
            $flag = 0;
        } elseif ($tmonth < 0 || $tmonth > 12) {
            $flag = 0;
        } elseif ($tday < 0 || $tday > 31) {
            $flag = 0;
        } else {
            if ($format) {
                $tdate = $tyear . "-" . $tmonth . "-" . $tday;
            } else {
                $tdate = $tmonth . "-" . $tday;
            }
            if ((time() - mktime(0, 0, 0, $tmonth, $tday, $tyear)) > 18 * 365 * 24 * 60 * 60) {
                $flag = 0;
            } else {
                $flag = 1;
            }
        }
        //获取身份证性别
        // $sex = substr($IDCard, (strlen($IDCard)==15 ? -2 : -1), 1) % 2 ? '1' : '0'; //1为男 2为女
        $sex = ((int) substr($IDCard, 16, 1))% 2 === 0 ? '女' : '男';
        //获取身份证年龄
        $year = substr($IDCard, 6, 4);
        $monthDay = substr($IDCard, 10, 4);
        $age = date('Y') - $year;
        if ($monthDay > date('md')) {
            $age--;
        }

    }
    $result['error'] = 2;//0：未知错误，1：身份证格式错误，2：无错误 
    $result['sex'] = $sex;//性别
    $result['age'] = $age;//年龄 
    $result['isAdult'] = $flag;//0标示成年，1标示未成年 
    $result['birthday'] = $tdate;//生日日期 
    return $result;
}

function checkProject()
{
    if (duetime()) {
        getaccess();
    }
    $hospitalid = session('hospitalid');
    $projectid = session('projectid');
    if (empty($hospitalid) || empty($projectid)) {
        echo "<p style='color:red;font-size:25px;margin-left:200px;'>请在右上角选择切换机构！</p>";
        exit;
    }
}

function getYypatientFujiaTime($type, $projectid, $yypatientid, $time)
{
    if ($type == 'huifang') {
        $modle = M('Yypatienthuifang');
    }
    if ($type == 'fuzhen') {
        $modle = M('Yypatientfuzhen');
    }
    if ($type == 'zhiliao') {
        $modle = M('Yypatientzhiliao');
    }
    $con['projectid'] = $projectid;
    $con['yypatientid'] = $yypatientid;
    $temptime = $modle->where($con)->order('nexttime desc')->getField('nexttime');
    // dump($temptime);
    // exit;
    return $temptime > $time ? $temptime : $time;
}
